package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"repo-manage/cache"
	"repo-manage/model"
	"strconv"
	"time"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	counter := c.PostForm("counter")
	price := c.PostForm("price")
	if title == "" || counter == "" || price == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Request{
		Title:   title,
		Price:   price,
		Counter: counter,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "hanzi" + strconv.Itoa(int(data.ID))
	var article model.Request
	model.DB.Where("id", data.ID).First(&article)
	JsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")

	err := model.DB.Where("id= ? ", id).Delete(&model.Request{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "Deslss" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var article []model.Request

	redis_key := "lsitds"
	CaretDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CaretDate == "" {
		model.DB.First(&article)
		Jsonss, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, Jsonss, time.Hour*2)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
